package 栈;

import java.util.Stack;

public class StringDecodingWithStack {


    //       3[a2[c]]  "3[a]2[bc]"
    public static String decodeString(String s) {
        Stack<Integer> numStack = new Stack<>(); // 存储重复次数的栈
        Stack<StringBuilder> currentResult = new Stack<>(); // 存储重复次数的栈
        int num = 0; // 存储当前的重复次数
        StringBuilder sb = new StringBuilder();

        char[] charArray = s.toCharArray();

        for (int i = 0; i < charArray.length; i++) {
            if (Character.isDigit(charArray[i])) {
                // 如果是数字，则解析数字
                num = num * 10 + Integer.parseInt(String.valueOf(charArray[i]));
            } else if (charArray[i] == '[') {
                // 如果是 '['，则将当前的重复次数和中间结果压栈
                numStack.push(num);
                num = 0; // 重置重复次数
                if(sb.length() > 0){
                    currentResult.push(sb);
                }
                sb = new StringBuilder(); //先干净做人 再放进去
                currentResult.push(sb);
            } else if (charArray[i] == ']') {
                // 如果是 ']'，则将栈顶的重复次数和中间结果弹出，并组合结果
                int repeatTimes = numStack.pop();
                StringBuilder thisItem = currentResult.pop();
                if(currentResult.isEmpty()){
                    sb = new StringBuilder();
                    for (int j = 0; j < repeatTimes; j++) {
                        sb.append(thisItem);
                    }
                    if(i == charArray.length-1){
                        return sb.toString();
                    }else{
                        currentResult.push(sb);
                    }
                }else{
                    for (int j = 0; j < repeatTimes; j++) {
                        currentResult.peek().append(thisItem);
                    }
                }
                sb = new StringBuilder(); //先干净做人 再放进去
            } else {
                // 如果是字母，则添加到当前字符串
                sb.append(charArray[i]);
                if(i == charArray.length-1) {
                    currentResult.peek().append(sb);
                }
            }

        }
        return currentResult.pop().toString();
    }

    public static void main(String[] args) {


        String encodedString2 = "2[abc]3[cd]ef";
        String decodedString2 = decodeString(encodedString2);
        System.out.println(encodedString2 + " 解码后: " + decodedString2); // 输出: 3[a2[c]] 解码后: accaccacc



    }
}